package com.smartleanx.module.hrm.service.tenant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smartleanx.framework.common.pojo.CommonResult;
import com.smartleanx.module.hrm.service.esign.service.HrmECustomComponentsService;
import com.smartleanx.module.hrm.service.esign.temp.po.HrmECustomComponents;
import com.smartleanx.module.system.api.tenant.TenantApi;

import cn.hutool.json.JSONObject;

@Slf4j
@Service
@InterceptorIgnore(tenantLine = "1")
public class TenantIgnoreIdService {

    @Resource
    private TenantApi tenantApi;

    @Resource
    private HrmECustomComponentsService customComponentsService;

    public void initTemplateComponent(Long tenantId) {
        CommonResult<List<JSONObject>> response = tenantApi.getTenantFieldId(tenantId);
        List<JSONObject> checkedData = response.getCheckedData();
        log.error("对应关系");
        log.error(JSON.toJSONString(checkedData));
        Map<String, String> mapData = checkedData.stream().collect(
            Collectors.toMap(item -> item.getStr("systemId"), item -> item.getStr("tenantId"),(existing, replacement) -> replacement));

        List<HrmECustomComponents> components =
            customComponentsService.list(new LambdaQueryWrapper<HrmECustomComponents>() {
                {
                    eq(HrmECustomComponents::getTenantId, 1);
                }
            });
        log.error("系统组件");
        log.error(JSON.toJSONString(components));
        for (HrmECustomComponents item : components) {
            item.setId(null);
            item.setComponentKey(mapData.get(item.getComponentKey()));
            item.setTenantId(tenantId);
        }
        log.error("新增组件");
        log.error(JSON.toJSONString(components));
        customComponentsService.saveBatch(components);
    }
}
